<template>
  <div class="category-container">
    <el-card class="category-card">
      <template #header>
        <div class="card-header">
          <span>公告列表</span>
        </div>
      </template>

      <el-table :data="announcements" border style="width: 100%" v-loading="loading">
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="公告标题" />
        <el-table-column label="发布时间" width="180">
          <template #default="scope">
            {{ scope.row.create_at }}
          </template>
        </el-table-column>
        <el-table-column label="是否置顶" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.is_pinned" type="warning">置顶</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        v-model:current-page="currentPage"
        layout="total, prev, pager, next, jumper"
        :total="totalAnnouncements"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="selectedAnnouncement?.title"
      width="60%"
    >
      <div v-if="selectedAnnouncement" class="announcement-detail">
        <div class="meta-info">
          <span>发布时间: {{ selectedAnnouncement.create_at }}</span>
          <span>发布人: {{ selectedAnnouncement.publisher || `用户${selectedAnnouncement.created_by_id}` }}</span>
          <el-tag v-if="selectedAnnouncement.is_pinned" type="warning">置顶</el-tag>
        </div>
        <el-divider />
        <div class="content" v-html="selectedAnnouncement.content"></div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import requestUtil from '@/util/request.js'
import { ElMessage } from 'element-plus'

// 时间格式化函数
const formatDate = (dateStr) => {
  if (!dateStr) return ''

  // 解析日期字符串
  const date = new Date(dateStr)

  // 获取年、月、日、时、分、秒
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  // 返回格式化后的字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 公告数据
const announcements = ref([])
const loading = ref(false)
const totalAnnouncements = ref(0)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10) // 固定每页10条

// 用户信息缓存
const userCache = new Map()

// 获取用户信息
const fetchUserInfo = async (userId) => {
  // 如果缓存中有，直接返回
  if (userCache.has(userId)) {
    return userCache.get(userId)
  }

  try {
    const response = await requestUtil.get(`/user/secret/msg/${userId}`)
    const userData = response.data.data[0]
    const username = userData?.username || `用户${userId}`

    // 存入缓存
    userCache.set(userId, username)
    return username
  } catch (error) {
    console.error(`获取用户 ${userId} 信息失败:`, error)
    return `用户${userId}`
  }
}

// 获取公告列表
const fetchAnnouncements = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value
    }

    const response = await requestUtil.get('/announcement/msg', params)

    // 对每个公告的创建时间进行格式化
    announcements.value = response.data.data.list.map(announcement => ({
      ...announcement,
      create_at: formatDate(announcement.create_at)
    }))

    totalAnnouncements.value = response.data.data.total
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取公告列表失败: ' + (error.message || '未知错误'))
    // 出错时确保数据是数组格式
    announcements.value = []
    totalAnnouncements.value = 0
  } finally {
    loading.value = false
  }
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAnnouncements()
}

// 公告详情
const detailDialogVisible = ref(false)
const selectedAnnouncement = ref(null)

const viewDetail = async (announcement) => {
  // 设置基础公告信息
  selectedAnnouncement.value = { ...announcement }

  // 获取发布者用户名
  try {
    const username = await fetchUserInfo(announcement.created_by_id)
    selectedAnnouncement.value.publisher = username
  } catch (error) {
    console.error('获取发布者信息失败:', error)
    selectedAnnouncement.value.publisher = `用户${announcement.created_by_id}`
  }

  detailDialogVisible.value = true
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAnnouncements()
})
</script>

<style lang="scss" scoped>
.category-container {
  padding: 20px 0;

  .category-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
    }
  }

  .pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}

.announcement-detail {
  padding: 20px;
}

.meta-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.content {
  line-height: 1.6;
}

.content >>> p {
  margin: 10px 0;
}

.dialog-footer {
  text-align: right;
}
</style>
